using System;
using System.Diagnostics;

namespace ArtSpec
{
    internal class SpecifyIt : ISpecifyIt, ISpec
    {
        public event Action OnBefore;
        public event Action OnAfter;
        public event Action<ISpec> OnResult;


        private readonly string description;
        private Action action;
        private bool verified;
        private Exception error;

        public SpecifyIt(string description, Action action)
        {
            this.description = description;
            this.action = action;
        }


        public string Description
        {
            get { return description; }
        }

        public Exception Error
        {
            get
            {
                Debug.Assert(verified, "Specification should be verified first");
                return error;
            }
        }

        public void Verify()
        {
            verified = true;
            if (action == null)
            {
                error = new SpecNotDefinedException();
                Fire.Event(OnResult, this);
                return;
            }

            OnBefore();
            try
            {
                action();
            }
            catch (Exception e)
            {
                error = e;
            }
            Fire.Event(OnResult, this);
            OnAfter();
        }
    }
}